package com.heima.wemedia.service.impl;

import apis.schedule.IScheduleClient;
import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.TaskDto;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.concurrent.*;

@Service
@Slf4j
public class WmNewTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 新增任务
     * 原因：如果在发布文章里面直接调用feign接口，那就会造成一个同步的问题
     * 所以需要单独写一个发布任务的方法，来调用feign的接口，然后将此接口设计成一个异步方法
     * 问题：提交审核任务之后，想重新修改怎么办？怎么删除数据库里面的旧任务
     *
     * @param id
     * @param publish
     */
    @Override
    @Async
    public void addNewsToTask(Integer id, Date publish) {
        TaskDto taskDto = new TaskDto();
        taskDto.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        taskDto.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        taskDto.setExecuteTime(publish.getTime());
        taskDto.setParameters(String.valueOf(id).getBytes());
        scheduleClient.add(taskDto);
    }


    /**
     * 获取任务
     */
    @Scheduled(fixedRate = 1000)
    @Override
    public void scanNewsByTask() {
        ResponseResult responseResult = scheduleClient.popTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (responseResult.getCode() == 200) {
            TaskDto taskDto = JSON.parseObject(JSON.toJSONString(responseResult.getData()), TaskDto.class);
            if (taskDto != null) {
                log.info("获取到了任务");
                wmNewsAutoScanService.autoScanWmNews(Integer.parseInt(new String(taskDto.getParameters())));
            }
        }
    }
//    @PostConstruct
//    public void demo() {
//        log.info("自动调用");
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                scanNewsByTask();
//            }
//        }).start();
//    }
//
//
//    public void scanNewsByTask() {
//        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
//        log.info("监听任务中");
//        while (true) {
//            log.info("等待中");
//            ResponseResult responseResult = scheduleClient.popTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
//            if (responseResult.getCode() == 200) {
//                TaskDto taskDto = JSON.parseObject(JSON.toJSONString(responseResult.getData()), TaskDto.class);
//                if (taskDto != null) {
//                    threadPoolExecutor.execute(new Runnable() {
//                        @Override
//                        public void run() {
//                            log.info("收到任务------------------------");
//                            wmNewsAutoScanService.autoScanWmNews(Integer.parseInt(new String(taskDto.getParameters())));
//                        }
//                    });
//                }
//            }
//        }
//    }
}
